package lagou.homework.lagou_homework_rocketmq.service.impl;

import lagou.homework.lagou_homework_rocketmq.entity.Order;
import lagou.homework.lagou_homework_rocketmq.entity.Seckill;
import lagou.homework.lagou_homework_rocketmq.exception.SeckillException;
import lagou.homework.lagou_homework_rocketmq.repository.GoodsRepository;
import lagou.homework.lagou_homework_rocketmq.repository.OrderRepository;
import lagou.homework.lagou_homework_rocketmq.repository.SeckillRepository;
import lagou.homework.lagou_homework_rocketmq.service.GoodsService;
import lagou.homework.lagou_homework_rocketmq.service.OrderService;
import lagou.homework.lagou_homework_rocketmq.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private SeckillRepository seckillRepository;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 支付账单
     * @param orderNo
     */
    @Override
    public String payOrder(String orderNo,String seckillId){
        log.info("支付{}订单",orderNo);
        String result = "支付成功";
        /**
         * 数据库查询order
         */
        Order order = orderRepository.findByOrderNo(orderNo);
        /**
         * 校验
         */
        //校验订单超时
        if(order.getStatus() == 2){
            return "订单支付超时";
        }
        if(order == null){
          return "没有对应订单";
        }
        /**
         * 支付
         */
        try {
            /**
             * 更改数据库
             */
            //修改订单状态
            orderRepository.updateOrderStatus(orderNo,1);
           //支付成功不减库存，但是支付失败或超时，要回滚库存
            order = orderRepository.findByOrderNo(orderNo);
            if(order.getUserId().equals("payFail")){
                throw new Exception("人造支付失败");
            }
            if(order.getUserId().equals("payTimeout")){
                Thread.sleep(30*1000);
            }
            log.info("支付成功");
            return "支付成功";
        } catch (Exception e) {
            log.error("支付失败",e);
            //回滚订单
            order.setStatus(3);
            rollback(order,seckillId);
           return "支付失败";
        }
    }

    /**
     * 订单状态回滚
     * @param order
     */
    @Transactional
    @Override
    public void rollback(Order order,String seckillId){
        log.error("订单{}回滚",order.getOrderNo());
        /**
         * 商品库存回滚
         */
        goodsService.increaseStock(order.getOrderNo(),order.getNum());
        /**
         * 回滚redis
         */
        if(seckillId != null){
            try {
                int killCount = seckillRepository.findById(seckillId).get().getKillCount();
                if(redisTemplate.hasKey("seckill" + seckillId + ":count")) {
                    redisTemplate.boundValueOps("seckill" + seckillId + ":count").increment(killCount);
               }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        /**
         * 订单状态设置
         */
        orderRepository.updateOrderStatus(order.getOrderNo(),order.getStatus());
    }
}
